package network2;

import java.io.IOException;
import java.net.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class UdpEchoClient {
    private DatagramSocket socket = null;
    private int serverPort;
    private String serverIp;

    public UdpEchoClient(String serverIp,int serverPort) throws SocketException {
//        实例化
        socket = new DatagramSocket();
        this.serverIp = serverIp;
        this.serverPort = serverPort;
    }

    public void start() throws IOException {
        System.out.println("客户端启动！");
        Scanner scanner = new Scanner(System.in);
        while(true){
//            1.从控制台读取字符串
            System.out.println("请输入需要发送的请求：");
            String request = scanner.next();
//            将内容进行打包
//            构造请求数据报时，不只是要有数据还需要有“目标”
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),0,request.getBytes().length,
                    InetAddress.getByName(serverIp),serverPort);
//            2.把字符串发送给服务器
            socket.send(requestPacket);
//            服务器流程
//            3.从服务器读取响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
//            4.将响应打印到控制台上
            String response = new String(responsePacket.getData(),0,responsePacket.getData().length);
            System.out.println(response);
        }
    }
    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1",9999);
        client.start();
    }
}
